package org.csu.chatserver.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.csu.chatserver.mapper.RoomMapper;
import org.csu.chatserver.mapper.RoomMessageMapper;
import org.csu.chatserver.mapper.UserMapper;
import org.csu.chatserver.entity.pojo.User;
import org.csu.chatserver.entity.pojo.Room;
import org.csu.chatserver.entity.pojo.RoomMessage;
import org.csu.chatserver.service.RoomMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RoomMessageServiceImpl implements RoomMessageService {

    @Autowired
    private RoomMessageMapper roomMessageMapper;

    @Autowired
    private RoomMapper roomMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean sendMessage(Integer roomId, Integer senderId, String context) {
         // 检查房间是否存在
         Room room = roomMapper.selectById(roomId);
         if (room == null) {
             return false;
         }
         
         // 检查发送者是否存在
         User user = userMapper.selectById(senderId);
         if (user == null) {
             return false;
         }
 
         RoomMessage message = new RoomMessage();
         message.setRoomId(roomId);
         message.setSenderId(senderId);
         message.setContent(context);
         message.setTime(LocalDateTime.now());
         
         return roomMessageMapper.insert(message) > 0;
    }

    @Override
    public List<RoomMessage> getRoomMessages(Integer roomId) {
        QueryWrapper<RoomMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roomid", roomId)
                   .orderByAsc("time");
        return roomMessageMapper.selectList(queryWrapper);
    }

    @Override
    public List<RoomMessage> getMessagesSince(Integer roomId, String timestamp) {
        QueryWrapper<RoomMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roomid", roomId)
                   .gt("time", timestamp)
                   .orderByAsc("time");
        return roomMessageMapper.selectList(queryWrapper);
    }

    @Override
    public boolean deleteMessage(Integer messageId) {
        return roomMessageMapper.deleteById(messageId) > 0;
    }
}